// ==UserScript==
// @name         N 网直接下载, 绕过等待
// @namespace    http://tampermonkey.net/
// @version      1.0.0
// @description  try to take over the world!
// @author       小莫
// @match        https://www.nexusmods.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=nexusmods.com
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    // 创建一个观察器实例并传入回调函数
    const observer = new MutationObserver((mutationsList, observer) => {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                let downloads = document.getElementsByClassName("accordion-downloads");
                if (downloads.length > 0) {
                    addDownloadButtons(downloads);
                    observer.disconnect(); // 检测到元素后关闭观察器
                    break;
                }
            }
        }
    });

    // 配置观察选项
    const config = { childList: true, subtree: true };

    // 传入目标节点和观察选项
    observer.observe(document.body, config);

    function addDownloadButtons(downloads) {
        let btn = document.createElement("li");
        let btnHtml = `
        <div class="btn inline-flex popup-btn-ajax"    
            data-tracking="[&quot;Mod Page&quot;,&quot;Download File&quot;,&quot;Manual Download&quot;]">
            <svg class="icon icon-manual">
                <use xlink:href="/assets/images/icons/icons.svg#icon-manual"></use>
            </svg>
            <span class="flex-label">直接下载</span>
        </div>`;
        btn.innerHTML = btnHtml;

        for (let i = 0; i < downloads.length; i++) {
            let item = downloads[i];

            console.log(item.innerHTML);
            // 在下载列表中添加按钮
            item.appendChild(btn.cloneNode(true));

            item.addEventListener("click", function (e) {
                //使用正则从 item.innerHTML =  https://www.nexusmods.com/Core/Libs/Common/Widgets/ModRequirementsPopUp?id=204&amp;game_id=6993   获取 id 和 game_id
                let id = item.innerHTML.match(/id=(\d+)/)[1];
                let game_id = item.innerHTML.match(/game_id=(\d+)/)[1];
                download(parseInt(id), parseInt(game_id));
            })
        }
    }

    function download(id, game_id) {
        let url = "https://www.nexusmods.com/Core/Libs/Common/Managers/Downloads?GenerateDownloadUrl";
        let formData = new FormData();
        formData.append('fid', id);
        formData.append('game_id', game_id);

        fetch(url, {
            method: 'POST',
            body: formData
        }).then(response => {
            response.json().then(data => {
                // 打开 data.url
                window.open(data.url);
            })
        })
    }

})();